package cn.ittaoli.movie.controller;

import cn.ittaoli.movie.model.Movie;
import cn.ittaoli.movie.service.AdminService;
import cn.ittaoli.movie.service.MovieService;
import cn.ittaoli.utils.FileUpload;
import cn.ittaoli.utils.JsonUtils;
import com.github.pagehelper.PageInfo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by lub_lenovo on 2017/11/2.
 */
@Controller
@RequestMapping("/movie")
public class MovieController {

    @Autowired
    private MovieService movieService;

    @RequestMapping("/add/menu/{menu}")
    public String add(@PathVariable("menu") String menu, Model model){
        model.addAttribute("menu",menu);
        return "/admin/movie_add";
    }

    @RequestMapping("/doAdd")
    @ResponseBody
    public Integer doAdd(Movie movie) throws IOException {
       return movieService.add(movie);
    }

    @RequestMapping("/upload")
    @ResponseBody
    public String upload(MultipartFile file, HttpServletRequest request) throws IOException {
        String path= FileUpload.upload(file,request);

        Map<String,Object> map=new HashMap();
        map.put("error",0);
        map.put("url",path);
        //return map;
        return JsonUtils.objectToJson(map);
    }


    @RequestMapping("/page")
    public String list(Model model){
        List<Movie> all = movieService.getAll();
        model.addAttribute("movies",all);
        return "/admin/movie_list";
    }

    @RequestMapping("/list/menu/{menu}")
    public String page(@PathVariable("menu") String menu,Model model,@RequestParam(value = "pageNum",defaultValue = "1") Integer pageNum,@RequestParam(value = "numPerPage",defaultValue = "2") Integer numPerPage){
        PageInfo pageInfo=movieService.getPagedData(pageNum,numPerPage);
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("menu",menu);

        return "/admin/movie_list";
    }

}
